package com.example.demo01.service;

import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.IBinder;
import android.util.Log;

import androidx.annotation.Nullable;

import com.example.demo01.R;
import com.example.demo01.consts.MyMediaPlayer;

//! 这里切记在AndroidManifest.xml中声明 <service ... />否则不认为是 Service
public class MyService extends Service {

    //用于播放音乐等媒体资源
    private MediaPlayer mediaPlayer;

    public MyService() {
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        if (mediaPlayer == null) {
            //. 创建媒体资源实例
            mediaPlayer = MediaPlayer.create(this, R.raw.music);
        }
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
//        String command = intent.getStringExtra("command");
        //! 这里常规写法需要引入常量，所以创建 MyMediaPlayer 常量库
        String command = intent.getStringExtra(MyMediaPlayer.COMMAND);

        if (command == null) return START_NOT_STICKY;

        switch (command) {
            case MyMediaPlayer.COMMAND_PLAY:
                play();
                break;
            case MyMediaPlayer.COMMAND_PAUSE:
                pause();
                break;
        }
        return START_STICKY;
    }

    //. 播放
    private void play() {
        if (!mediaPlayer.isPlaying()) {
            mediaPlayer.start();
        }
        Log.i("TAG", "播放中");
    }

    //. 暂停
    private void pause() {
        if (mediaPlayer.isPlaying()) {
            mediaPlayer.pause();
        }
        Log.i("TAG", "已暂停");
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        releaseMediaPlayer();
        Log.i("TAG", "服务销毁");
    }

    private void releaseMediaPlayer() {
        if (mediaPlayer != null) {
            try {
                mediaPlayer.stop();
                mediaPlayer.release();
            } catch (Exception e) {
                Log.e("TAG", "释放MediaPlayer失败", e);
            } finally {
                mediaPlayer = null;
            }
        }
    }
}
